﻿Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32


Public Class frmCapture


    Inherits System.Windows.Forms.Form

    Const WM_CAP_START = &H400S
    Const WS_CHILD = &H40000000
    Const WS_VISIBLE = &H10000000

    Const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10
    Const WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11
    Const WM_CAP_EDIT_COPY = WM_CAP_START + 30
    Const WM_CAP_SEQUENCE = WM_CAP_START + 62
    Const WM_CAP_FILE_SAVEAS = WM_CAP_START + 23

    Const WM_CAP_SET_SCALE = WM_CAP_START + 53
    Const WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52
    Const WM_CAP_SET_PREVIEW = WM_CAP_START + 50

    Const SWP_NOMOVE = &H2S
    Const SWP_NOSIZE = 1
    Const SWP_NOZORDER = &H4S
    Const HWND_BOTTOM = 1
    '--The capGetDriverDescription function retrieves the version
    ' description of the capture driver--
    Declare Function capGetDriverDescriptionA Lib "avicap32.dll" _
    (ByVal wDriverIndex As Short, _
    ByVal lpszName As String, ByVal cbName As Integer, _
    ByVal lpszVer As String, _
    ByVal cbVer As Integer) As Boolean

    '--The capCreateCaptureWindow function creates a capture window--
    Declare Function capCreateCaptureWindowA Lib "avicap32.dll" _
    (ByVal lpszWindowName As String, ByVal dwStyle As Integer, _
    ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, _
    ByVal nHeight As Short, ByVal hWnd As Integer, _
    ByVal nID As Integer) As Integer

    '--This function sends the specified message to a window or windows--
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Integer, ByVal Msg As Integer, _
    ByVal wParam As Integer, _
    <MarshalAs(UnmanagedType.AsAny)> ByVal lParam As Object) As Integer

    '--Sets the position of the window relative to the screen buffer--
    Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" _
    (ByVal hwnd As Integer, _
    ByVal hWndInsertAfter As Integer, ByVal x As Integer, _
    ByVal y As Integer, _
    ByVal cx As Integer, ByVal cy As Integer, _
    ByVal wFlags As Integer) As Integer

    '--This function destroys the specified window--
    Declare Function DestroyWindow Lib "user32" _
    (ByVal hndw As Integer) As Boolean

    '---used to identify the video source---
    Dim CamSource As Integer
    '---used as a window handle---
    Dim hWnd As Integer
    Dim SavePath As String = "C:\img\"

    Private Sub cameraSource()
        Dim DriverName As String = Space(80)
        Dim DriverVersion As String = Space(80)
        For i As Integer = 0 To 9
            If capGetDriverDescriptionA(i, DriverName, 80, _
            DriverVersion, 80) Then
                ListBox1.Items.Add(DriverName.Trim)
            End If
        Next
    End Sub

    Private Sub LoadDeviceList()
        Dim strName As String = Space(100)
        Dim strVer As String = Space(100)
        Dim bReturn As Boolean
        Dim x As Integer = 0

        ' Load name of all avialable devices into the lstDevices .

        Do
            '   Get Driver name and version
            bReturn = capGetDriverDescriptionA(x, strName, 100, strVer, 100)
            ' If there was a device add device name to the list 
            If bReturn Then ListBox1.Items.Add(strName.Trim)
            x += 1
        Loop Until bReturn = False
    End Sub

    Private Sub previewCamera(ByVal pbCtrl As PictureBox)
        hWnd = capCreateCaptureWindowA(CamSource, _
        WS_VISIBLE Or WS_CHILD, 0, 0, 0, _
        0, pbCtrl.Handle.ToInt32, 0)
        If SendMessage( _
        hWnd, WM_CAP_DRIVER_CONNECT, _
        CamSource, 0) Then

            '---set the preview scale---
            SendMessage(hWnd, WM_CAP_SET_SCALE, True, 0)
            '---set the preview rate (ms)---
            SendMessage(hWnd, WM_CAP_SET_PREVIEWRATE, 30, 0)
            '---start previewing the image---
            SendMessage(hWnd, WM_CAP_SET_PREVIEW, True, 0)
            '---resize window to fit in PictureBox control---
            SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, _
            pbCtrl.Width, pbCtrl.Height, _
            SWP_NOMOVE Or SWP_NOZORDER)
        Else
            '--error connecting to video source---
            DestroyWindow(hWnd)
        End If
    End Sub
    Private Sub stopPreviewCamera()
        SendMessage(hWnd, WM_CAP_DRIVER_DISCONNECT, CamSource, 0)
        DestroyWindow(hWnd)
        'Me.PictureBox1.Image.Dispose()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'cameraSource()
        LoadDeviceList()
        btnPreview.Enabled = False
        btnStopPreview.Enabled = False
        btnRecord.Enabled = False
        btnStopRecord.Enabled = False
        btnCapture.Enabled = False
        Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
        'Me.SaveFileDialog1.FileName = "img_" + Format(Now, "yyyyMMddhhmmss")
        'Me.SaveFileDialog1.Filter = "PNG|*.png"

    End Sub

    Private Sub ListBox1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
        Label1.Visible = False
        previewCamera(PictureBox1)
        btnStopPreview.Enabled = True
        btnPreview.Enabled = False
        btnRecord.Enabled = True
        btnCapture.Enabled = True

    End Sub

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        CamSource = ListBox1.SelectedIndex
        '---preview the selected video source
    End Sub
    ' recording
    Private Sub btnRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecord.Click
        btnStopRecord.Enabled = True
        btnRecord.Enabled = False
        SendMessage(hWnd, WM_CAP_SEQUENCE, 0, 0)
    End Sub

    ' stop recording and ask to save video
    Private Sub btnStopRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopRecord.Click
        Dim save As Integer
        save = MsgBox("Do you want to save your recording video", MsgBoxStyle.YesNo + MsgBoxStyle.Information, "Recording Video")
        If (save = MsgBoxResult.Yes) Then
            Dim saveName As New SaveFileDialog
            saveName.Filter = "Avi file(*.avi)|*.avi"
            If saveName.ShowDialog = DialogResult.OK Then
                ' SendMessage(hWnd, WM_CAP_FILE_SAVEAS, 0, "C:\RecordedVideo.avi")
                SendMessage(hWnd, WM_CAP_FILE_SAVEAS, 0, saveName.FileName)
            End If
        End If
        Me.Cursor = System.Windows.Forms.Cursors.Default
        btnRecord.Enabled = True
        btnStopRecord.Enabled = False
    End Sub

    ' preview
    Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
        CamSource = ListBox1.SelectedIndex
        previewCamera(PictureBox1)
        btnPreview.Enabled = False
        btnStopPreview.Enabled = True
        btnCapture.Enabled = True
    End Sub

    'stop preview
    Private Sub btnStopPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopPreview.Click
        stopPreviewCamera()
        btnPreview.Enabled = True
        btnStopPreview.Enabled = False
        btnCapture.Enabled = False
    End Sub

    Private Sub btnCapture_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapture.Click
        Dim data As IDataObject
        Dim bmap As Image

        Dim SaveFileName As String

        SaveFileDialog1.Filter = "image files (*.png;*.jpg)|*.png;*.jpg"
        SaveFileName = "img_" + Format(Now, "yyyyMMddhhmmss")
        SavePath = SavePath & SaveFileName
        Me.SaveFileDialog1.FileName = SaveFileName

        SendMessage(hWnd, WM_CAP_EDIT_COPY, 0, 0)
        data = Clipboard.GetDataObject()

        If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
            bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Image)


            stopPreviewCamera()
            ' Me.btnPreview.Enabled = True

            'chkShowDialogSave
            If chkShowDialogSave.Checked Then

                bmap.Save(SavePath, Imaging.ImageFormat.Png)

                '----------
                'If LayoutPanelImage.Controls.Count = 0 Then
                'Dim i = 0

                Dim pb = New PictureBox()
                Dim loadedImage = Image.FromFile(SavePath)
                pb.Height = 100
                pb.Width = 150
                pb.Name = SaveFileName
                pb.Image = loadedImage
                pb.SizeMode = PictureBoxSizeMode.StretchImage
                LayoutPanelImage.Controls.Add(pb)

                'Else
                '    Dim i = LayoutPanelImage.Controls.Count

                '    Dim pb = New PictureBox()
                '    Dim loadedImage = Image.FromFile(Me.SaveFileDialog1.FileName)
                '    pb.Height = 100
                '    pb.Width = 150
                '    pb.Image = loadedImage
                '    pb.SizeMode = PictureBoxSizeMode.StretchImage
                '    LayoutPanelImage.Controls.Add(pb)

                'End If
                ''----------

            Else
                If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
                    bmap.Save(Me.SaveFileDialog1.FileName, Imaging.ImageFormat.Png)
                End If

                '----------
                'If LayoutPanelImage.Controls.Count = 0 Then
                '    Dim i = 0

                Dim pb = New PictureBox()
                Dim loadedImage = Image.FromFile(Me.SaveFileDialog1.FileName)
                pb.Height = 100
                pb.Width = 150
                pb.Image = loadedImage
                pb.SizeMode = PictureBoxSizeMode.StretchImage
                LayoutPanelImage.Controls.Add(pb)

                'Else
                '    Dim i = LayoutPanelImage.Controls.Count

                '    Dim pb = New PictureBox()
                '    Dim loadedImage = Image.FromFile(Me.SaveFileDialog1.FileName)
                '    pb.Height = 100
                '    pb.Width = 150
                '    pb.Image = loadedImage
                '    pb.SizeMode = PictureBoxSizeMode.StretchImage
                '    LayoutPanelImage.Controls.Add(pb)

                'End If
                '----------
            End If


            'If Me.SaveFileDialog1.ShowDialog = DialogResult.OK Then
            ' bmap.Save(Me.SaveFileDialog1.FileName, Imaging.ImageFormat.Bmp)
            'End If

            '------------
            Me.PictureBox2.Image = bmap
            Me.PictureBox2.SizeMode = PictureBoxSizeMode.StretchImage

            previewCamera(PictureBox1)


        End If
    End Sub

    Private Sub btnShowPicture_Click(sender As System.Object, e As System.EventArgs) Handles btnShowPicture.Click
        'flowLayoutPanel.Controls.Clear ;
        OpenFileDialog1.Multiselect = True
        OpenFileDialog1.Title = "My Image Browser"
        'OpenFileDialog1.Filter = "JPEG files (*.jpg)|*.jpg|GIF files (*.gif)|*.gif|All files (*.*)|*.*"
        OpenFileDialog1.Filter = "image files (*.bmp;*.jpg;*.jpeg;*.png;*.gif;*.tif;*.tiff)|*.bmp;*.jpg;*.jpeg;*.png;*.gif;*.tif;*.tiff"
        OpenFileDialog1.InitialDirectory = "C:\img\"
        OpenFileDialog1.RestoreDirectory = True
        LayoutPanelImage.Controls.Clear()

        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            For Each file In OpenFileDialog1.FileNames
                Dim lbl As New Label
                'With lbl
                '.Text = file

                Dim pb = New PictureBox()
                Dim loadedImage = Image.FromFile(file)
                pb.Height = 100
                pb.Width = 150
                pb.Image = loadedImage
                pb.SizeMode = PictureBoxSizeMode.StretchImage


                ' End With
                LayoutPanelImage.Controls.Add(pb)
            Next
        End If

    End Sub

    Private Sub LayoutPanelImage_Click(sender As Object, e As System.EventArgs) Handles LayoutPanelImage.Click
        Dim ImageName As String
        'If LayoutPanelImage.Controls.Count = 0 Then
        'Dim i = 0
        'ImageName = LayoutPanelImage.Controls.Count

        'Dim strFileName As String = DirectCast(sender, PictureBox).Tag.ToString
        'MsgBox(strFileName.ToString)
        'Process.Start(strFileName)
        'MessageBox.Show(LayoutPanelImage.VerticalScroll.Maximum.ToString())

    End Sub



    Private Sub LayoutPanelImage_MouseHover(sender As Object, e As System.EventArgs) Handles LayoutPanelImage.MouseHover
        Dim ImageName As String
        'If LayoutPanelImage.Controls.Count = 0 Then
        'Dim i = 0
        'ImageName = LayoutPanelImage.DataBindings.Count


        'MsgBox("ค่าที่ตั้งไม่สามารถติดต่อฐานข้อมูลได้ กรุณากรอกข้อมูลใหม่อีกครั้ง", MsgBoxStyle.Information, "ไม่สามารถปรับปรุงการตั้งค่าได้")
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If MsgBox("Do you want delete all image ? ", vbYesNo, "Confirm") = vbYes Then
            'Dim i As Integer = 0
            Dim ControlCount As Integer = LayoutPanelImage.Controls.Count
            Do Until 1 > ControlCount
                LayoutPanelImage.Controls.RemoveAt(ControlCount - 1)
                ControlCount -= 1
            Loop
            LayoutPanelImage.Refresh()
            'MsgBox("Image = " & LayoutPanelImage.Controls.Count, MsgBoxStyle.Information, "data")
        Else

            
            LayoutPanelImage.Controls.RemoveAt(LayoutPanelImage.Controls.Count - 1)
            'Dim ImageName As String = LayoutPanelImage.Controls.Item(LayoutPanelImage.Controls.Count - 1).Name
            'MsgBox("Image = " & ImageName, MsgBoxStyle.Information, "data")
            
            LayoutPanelImage.Refresh()


        End If

    End Sub
End Class
